/**
 * @Created by Webstorm
 * @Author: 打字桶
 * @Desc
 */
import wxToPromise from "./wx";
import APIConfig from "../config/api";
import Http from "./http";

class FileUploader extends Http {
  static async upload(filePath, key = 'file') {
    // wx.uploadFile本身不支持返回promise 需要调用 wxToPromise
    let res
    try {
      res = await wxToPromise('uploadFile', {
        url: APIConfig.baseUrl + '/v1/file',
        filePath,
        name: key
      })
    } catch (e) {
      FileUploader._showError(-1)
      throw Error(e.errMsg)
    }

    // uploadFile返回的结果是字符串,需要转成对象
    const serveData = JSON.parse(res.data);

    if (res.statusCode !== 201) {
      FileUploader._showError(serveData.error_code, serveData.message)
      throw Error(serveData.message)
    }
    return serveData.data
  }
}

export default FileUploader
